//
//  LogCatContactHelper.m
//  LogCat
//
//  Created by 清风徐来 on 2024/1/8.
//

#import "LogCatContactHelper.h"
#import <Contacts/Contacts.h>

@implementation LogCatContactHelper

static LogCatContactHelper *_sharedInstance;
+ (instancetype)shared {
    if(_sharedInstance == nil) {
        _sharedInstance = [[LogCatContactHelper alloc] init];
    }
    return _sharedInstance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [super allocWithZone:zone];
    });
    return _sharedInstance;
}

- (id)copyWithZone:(NSZone *)zone {
    return _sharedInstance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _sharedInstance;
}

// 检查通讯录访问权限的方法，包含回调
- (void)checkContactsAccessWithCompletion:(ContactsAccessCompletion)completion {
    CNContactStore *store = [[CNContactStore alloc] init];

    switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]) {
        case CNAuthorizationStatusNotDetermined: {
            // 权限未确定，请求权限
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    // 权限被授予
                    if (completion) {
                        completion(YES);
                    }
                } else {
                    // 权限被拒绝
                    if (completion) {
                        completion(NO);
                    }
                }
            }];
            break;
        }
        case CNAuthorizationStatusRestricted:
        case CNAuthorizationStatusDenied:
            // 权限被限制或拒绝
            if (completion) {
                completion(NO);
            }
            break;
        case CNAuthorizationStatusAuthorized:
            // 权限已被授予
            if (completion) {
                completion(YES);
            }
            break;
    }
}

// 获取通讯录并转换为JSON字符串
- (NSString *)fetchContactsAndConvertToJSON {
    CNContactStore *store = [[CNContactStore alloc] init];
    NSError *error;
    NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    NSMutableArray *contactsArray = [NSMutableArray array];

    [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSMutableArray *phoneNumbersArray = [NSMutableArray array];
        for (CNLabeledValue *label in contact.phoneNumbers) {
            CNPhoneNumber *phoneNumber = label.value;
            [phoneNumbersArray addObject:phoneNumber.stringValue];
        }

        NSDictionary *contactDict = @{
            @"firstName": contact.givenName,
            @"lastName": contact.familyName,
            @"phoneNumbers": phoneNumbersArray
        };

        [contactsArray addObject:contactDict];
    }];

    if (!error) {
        NSError *jsonError;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contactsArray options:NSJSONWritingPrettyPrinted error:&jsonError];

        if (!jsonError) {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            return jsonString; // 返回JSON字符串
        } else {
            NSLog(@"JSON Error: %@", jsonError.localizedDescription);
            return nil; // 或返回空字符串 @""
        }
    } else {
        NSLog(@"Error fetching contacts: %@", error.localizedDescription);
        return nil; // 或返回空字符串 @""
    }
}


@end
